package com.example.resubmit.domain;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 重复提交锁
 */
@Slf4j
@Component
public class ResubmitLock {
    @Autowired
    private RedissonClient redissonClient;

    public String handleKey(String param) {
        return DigestUtils.md5Hex(param == null ? "" : param);
    }

    /**
     * @param key 对应的key MD5加密
     * @return 加锁结果
     */
    public boolean lock(final String key) {
        RLock lock = redissonClient.getLock(key);

        boolean isLocked = lock.isLocked();
        if (isLocked) {
            return false;
        }

        boolean interrupted = false;
        try {
            return lock.tryLock(100, 30, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("防重复redis加锁失败, {}", e.getMessage());
            interrupted = true;
            return false;
        } finally {
            if (interrupted) {
                Thread.currentThread().interrupt();
            }
        }
    }
}